//
//  UserAccountViewModel.swift
//  SinaWeibo
//
//  Created by apple on 15/11/11.
//  Copyright © 2015年 apple. All rights reserved.
//

import UIKit
import AFNetworking

class UserAccountViewModel: NSObject {
    
    //增加用户 token 属性
    var account:UserAccount?
    
    /**
    在构造方法中给用户信息赋值
    */
    override init() {
        
        account = UserAccount.loadAccount()
    }
    
    //增加用户是否登录属性
    var userLogin: Bool {
        
        return account?.access_token != nil
    }
    //用户名属性
    var name :String? {
        
        return account?.name
    }
    
    //用户头像的地址
    var headURL:NSURL? {
        
        return NSURL(string: (account?.avatar_large ?? ""))
    }
    //定义 token 属性
    var token : String?{
        
        return account?.access_token
    }
    //通过code 获取用户de  Token 的值
    func loadAccessToken(code: String,finshed:(error:NSError?) -> ()) {
        
        let urlString = "oauth2/access_token"
        
        
        let parameters = ["client_id": client_id,"client_secret":client_secret,"grant_type" : "authorization_code","code":code,"redirect_uri":redirect_uri]
        
        NetWorkingTools.shareTools.requestJSONDict(.POST, urlString: urlString, parameters: parameters) { (result, error) -> () in
            
            if error != nil {
                
                print(error)
                
                //执行回调
                finshed(error: error)
                
                return
            }
            print(result)
            //开始字典转模型
            let account = UserAccount(dict:result!)
            self.loadUserInfo(account, finshed: finshed)
            
        }
    }
    
    //获取用户的详细信息
    private func loadUserInfo (account:UserAccount,finshed:(error:NSError?) -> ()) {
        
        let urlString = "https://api.weibo.com/2/users/show.json"
        
        let parameters = ["access_token":account.access_token!,"uid":account.uid!]
        
        NetWorkingTools.shareTools.requestJSONDict(.GET, urlString: urlString, parameters: parameters) { (result, error) -> () in
            
            if error != nil {
                
                finshed(error: error)
                
                return
            }
            
            account.avatar_large = result!["avatar_large"] as? String
            
            account.name = result!["name"] as? String
            
            account.saveAccount()
            
            //执行闭包
            finshed(error: nil)
            
        }
        
    }
    
}
